package com.zwf.service.impl;

import com.zwf.dto.GoodsSalesDTO;
import com.zwf.entity.OrderDetail;
import com.zwf.entity.Orders;
import com.zwf.mapper.OrderDetailMapper;
import com.zwf.mapper.OrderMapper;
import com.zwf.mapper.UserMapper;
import com.zwf.service.ReportService;
import com.zwf.service.WorkSpaceService;
import com.zwf.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author zwf
 * @date 2024/2/20 13:15
 */
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    WorkSpaceService workSpaceService;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {

        //用于存放日期
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);

        //用于存放当天营业额
        List<Double> turnoverList=new ArrayList<>();

        //获取时间段所有日期
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        //获取时间段每天对应的营业额
        dateList.forEach(date->{
            LocalDateTime beginTime=LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(date,LocalTime.MAX);
            Map map=new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover=orderMapper.sumTurnoverByMap(map);
            turnover=turnover==null?0.0:turnover;
            turnoverList.add(turnover);
        });

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {

        //用于存放日期
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);

        //用于存放用户总数
        List<Integer> totalUserList=new ArrayList<>();

        //用于存放新增用户数
        List<Integer> newUserList=new ArrayList<>();

        //获取时间段所有日期
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        dateList.forEach(date->{
            LocalDateTime beginTime=LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(date,LocalTime.MAX);
            Map map=new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            Integer newUser=userMapper.countByMap(map);
            newUser=newUser==null?0:newUser;

            map.put("begin",null);
            Integer totalUser=userMapper.countByMap(map);
            totalUser=totalUser==null?0:totalUser;

            totalUserList.add(totalUser);
            newUserList.add(newUser);
        });

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {

        //保存begin
        LocalDate beginSource=begin;

        //用于存放日期
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);

        //每日订单数
        List<Integer> orderList=new ArrayList<>();

        //每日有效订单数
        List<Integer> validOrderList=new ArrayList<>();

        //获取时间段所有日期
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        dateList.forEach(date->{
            LocalDateTime beginTime=LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(date,LocalTime.MAX);

            //获取每日订单总数
            Map map=new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            Integer orderCount=orderMapper.countByMap(map);
            orderList.add(orderCount);

            //获取每日有效订单数
            map.put("status",Orders.COMPLETED);
            Integer validOrderCount = orderMapper.countByMap(map);
            validOrderList.add(validOrderCount);

        });

        LocalDateTime beginTime=LocalDateTime.of(beginSource,LocalTime.MIN);
        LocalDateTime endTime=LocalDateTime.of(end,LocalTime.MAX);

        //获取订单总数
        Map map=new HashMap();
        map.put("begin",beginTime);
        map.put("end",endTime);
        Integer orderAllCount=orderMapper.countByMap(map);

        //获取有效订单总数
        map.put("status",Orders.COMPLETED);
        Integer validOrderAllCount = orderMapper.countByMap(map);

        //总订单完成率
        Double orderCompletionRate=0.0;
        if(orderAllCount!=0){
            orderCompletionRate=Double.valueOf(validOrderAllCount)/Double.valueOf(orderAllCount);
        }

        OrderReportVO orderReportVO=new OrderReportVO();
        orderReportVO.setDateList(StringUtils.join(dateList,","));
        orderReportVO.setOrderCountList(StringUtils.join(orderList,","));
        orderReportVO.setValidOrderCountList(StringUtils.join(validOrderList,","));
        orderReportVO.setTotalOrderCount(orderAllCount);
        orderReportVO.setValidOrderCount(validOrderAllCount);
        orderReportVO.setOrderCompletionRate(orderCompletionRate);

        return orderReportVO;
    }

    /**
     * 查询销量排名top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {

        LocalDateTime beginTime=LocalDateTime.of(begin,LocalTime.MIN);
        LocalDateTime endTime=LocalDateTime.of(end,LocalTime.MAX);

        Map map=new HashMap();
        map.put("begin",beginTime);
        map.put("end",endTime);

        //存放商品名称
        List<String> shopNameList= new ArrayList<>();

        //存放商品部销量
        List<Integer> shopSalesList=new ArrayList<>();

        List<GoodsSalesDTO> goodsSalesDTOList=orderDetailMapper.listGoodsSalesByMap(map);
        goodsSalesDTOList.forEach(goodsSalesDTO -> {
            shopNameList.add(goodsSalesDTO.getName());
            shopSalesList.add(goodsSalesDTO.getNumber());
        });

        SalesTop10ReportVO salesTop10ReportVO=new SalesTop10ReportVO();
        salesTop10ReportVO.setNameList(StringUtils.join(shopNameList,","));
        salesTop10ReportVO.setNumberList(StringUtils.join(shopSalesList,","));
        return salesTop10ReportVO;
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) throws IOException {

        //查询数据库，获取最近30天营业数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        BusinessDataVO businessDataVO = workSpaceService.businessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        XSSFWorkbook excel = new XSSFWorkbook(in);

        //填充数据
        //获取表格文件的Sheet页
        XSSFSheet sheet = excel.getSheet("Sheet1");

        //填充数据--时间
        sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

        //获得第4行
        XSSFRow row = sheet.getRow(3);
        row.getCell(2).setCellValue(businessDataVO.getTurnover());
        row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
        row.getCell(6).setCellValue(businessDataVO.getNewUsers());

        //获得第5行
        row = sheet.getRow(4);
        row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
        row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

        //填充明细数据
        for (int i = 0; i < 30; i++) {
            LocalDate date = dateBegin.plusDays(i);
            //查询某一天的营业数据
            BusinessDataVO businessData = workSpaceService.businessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

            //获得某一行
            row = sheet.getRow(7 + i);
            row.getCell(1).setCellValue(date.toString());
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(3).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessData.getUnitPrice());
            row.getCell(6).setCellValue(businessData.getNewUsers());
        }
        //通过输出流将Excel文件下载到客户端浏览器
        ServletOutputStream out = response.getOutputStream();
        excel.write(out);

        //关闭资源
        out.close();
        excel.close();
    }
}
